﻿using System.IO;
using System;
using System.Collections.Generic;

using System.Text;

namespace xReplace
{
    class DeleteCommand : AbstractProcessingCommand
    {
        public DeleteCommand(ref Content pipes) :base(ref pipes)
        {
        }

        public override bool ProcessCommand(System.Xml.XmlNodeList param)
        {
            string fromLabel = GetNodeValue("fromlabel", param);
            string toLabel = GetNodeValue("tolabel", param);
            string src = GetNodeValue("match", param);
            string startsWith = GetNodeValue("startswith", param);
            string endsWith = GetNodeValue("endswith", param);
            string skipStart = GetNodeValue("skipstart", param);
            string skipEnd = GetNodeValue("skipend", param);
            if (GetNodeAttributeAsBoolean("startswith", "escape", param))
                startsWith = SpecialCharHelper.Unescape(startsWith);
            if (GetNodeAttributeAsBoolean("endswith", "escape", param))
                endsWith = SpecialCharHelper.Unescape(endsWith);
            if (GetNodeAttributeAsBoolean("match", "escape", param))
                src = SpecialCharHelper.Unescape(src);
            if (GetNodeAttributeAsBoolean("skipstart", "escape", param))
                skipStart= SpecialCharHelper.Unescape(skipStart);
            if (GetNodeAttributeAsBoolean("skipend", "escape", param))
                skipEnd = SpecialCharHelper.Unescape(skipEnd);

            string ignoreCaseStr = GetNodeValue("ignorecase", param);
            bool ignoreCase = (ignoreCaseStr.ToLower() == "true") ? true : false;

            fromLabel = (fromLabel == "") ? Content.DEFAULT_KEY : fromLabel;
            toLabel = (toLabel == "") ? Content.DEFAULT_KEY : toLabel;

            string tmp = contentPipelines.LoadContent(fromLabel);
            if ((startsWith != "") && (endsWith != ""))
            {
                TextFragment frag = new TextFragment(tmp);
                while (frag.GrabFragment(startsWith, endsWith, skipStart, skipEnd, ignoreCase))
                {
                    tmp = tmp.Replace(frag.Fragment, "");
                }
            }
            else if (src != "")
            {
                tmp = tmp.Replace(src, "");
            }
            contentPipelines.StoreContent(toLabel, tmp);
            return true;
        }

    }
}
